<?php
// @formatter:off
/**
 * @file tools.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-06-07 02:16:25 +0000 (Fri, 07 Jun 2013) $
 *
 * $Id: tools.php 71 2013-06-07 02:16:25Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0-BETA1/includes/tools.php $
 */
// @formatter:on

class WCColorText {
	public static $nocolor = false;

	public static function ShellBlue($text) {
		return DIRECTORY_SEPARATOR == "/" && !self::$nocolor ? "\034[1;33m{$text}\033[0m" : $text;
	}
	public static function ShellGreen($text) {
		return DIRECTORY_SEPARATOR == "/" && !self::$nocolor ? "\033[1;32m{$text}\033[0m" : $text;
	}
	public static function ShellPurple($text) {
		return DIRECTORY_SEPARATOR == "/" && !self::$nocolor ? "\035[1;33m{$text}\033[0m" : $text;
	}
	public static function ShellRed($text) {
		return DIRECTORY_SEPARATOR == "/" && !self::$nocolor ? "\033[1;31m{$text}\033[0m" : $text;
	}
	public static function ShellYellow($text) {
		return DIRECTORY_SEPARATOR == "/" && !self::$nocolor ? "\033[1;33m{$text}\033[0m" : $text;
	}
}

class WCSanitizer {
	public static function IsAbsolutePath($path) {
		$out = false;
		if(DIRECTORY_SEPARATOR == "/") {
			$out = substr($path, 0, 1) == "/";
		} else {
			$out = substr($path, 1, 2) == ":\\";
		}

		return $out;
	}
	public static function SystemPath($path) {
		$out = str_replace(array(
			"/",
			"\\"
		), DIRECTORY_SEPARATOR, $path);

		$auxSeparator = DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR;
		while(($pos = strpos($out, $auxSeparator)) !== false) {
			$out = str_replace($auxSeparator, DIRECTORY_SEPARATOR, $out);
		}

		if($out[strlen($out) - 1] == DIRECTORY_SEPARATOR) {
			$out = substr($out, 0, strlen($out) - 1);
		}

		return $out;
	}
	public static function UrlEncode($var) {
		global $wcReplaceURL;
		return str_replace($wcReplaceURL["in"], $wcReplaceURL["out"], $var);
	}
	public static function UrlDecode($var) {
		global $wcReplaceURL;
		return str_replace($wcReplaceURL["out"], $wcReplaceURL["in"], $var);
	}
	public static function WComixPath($path) {
		$out = str_replace("\\", "/", $path);

		while(($pos = strpos($out, "//")) !== false) {
			$out = str_replace("//", "/", $out);
		}

		if($out[strlen($out) - 1] == '/') {
			$out = substr($out, 0, strlen($out) - 1);
		}

		return $out;
	}
}

function turlencode($var) {
	global $wcReplaceURL;
	return str_replace($wcReplaceURL["in"], $wcReplaceURL["out"], $var);
}
function turldecode($var) {
	global $wcReplaceURL;
	return str_replace($wcReplaceURL["out"], $wcReplaceURL["in"], $var);
}
/**
 * Seeks inside a directory for files and subdirectories.
 *
 * @param string $basicDir Directory to be searched.
 * @param string $linkDir This string will be used to generate URI path.
 * @param array $paths List of found paths. Every element of this array will be an
 * instance of ImagePath.
 * @param array $patterns List of file patterns to be searched. En example of this
 * is $wcPatterns["image-paths"].
 * @param boolean $allOfThem By default this parameter is false, meaning it must
 * bring only the first found entry.
 */
function findPaths($basicDir, $linkDir, &$paths, &$patterns, $allOfThem = false) {
	global $wcDefaults;

	if(!is_array($paths)) {
		$paths = array();
	}

	$dir = @dir("{$basicDir}");
	$done = false;
	if($dir) {
		while(!$done && false !== ($entry = $dir->read())) {
			if($entry != "." && $entry != "..") {
				if(!$wcDefaults["allow-hiddens"] && strpos($entry, ".") === 0) {
					continue;
				}
				if(is_dir($basicDir.DIRECTORY_SEPARATOR.$entry)) {
					findPaths($basicDir.DIRECTORY_SEPARATOR.$entry, $linkDir.DIRECTORY_SEPARATOR.$entry, $paths, $patterns, $allOfThem);
					if(!$allOfThem && count($paths)) {
						$done = true;
					}
				} else {
					if(is_array($patterns)) {
						foreach($patterns as $pat) {
							if(preg_match($pat, $entry)) {
								$img = new ImagePath();
								$img->path = $basicDir.DIRECTORY_SEPARATOR.$entry;
								$img->lpath = "{$linkDir}/{$entry}";
								$img->name = $entry;
								$img->ext = explode(".", $entry);
								$img->ext = $img->ext[count($img->ext) - 1];

								$paths[$img->path] = $img;

								if(!$allOfThem) {
									$done = true;
								}
								break;
							}
						}
					}
				}
			}
		}

		$dir->close();
	} else {
		$done = true;
	}

	sort($paths);
}
/**
 * This function builds a URI parameters list (starting from '?') based on current
 * URL and requested parameters.
 *
 * @param boolean $addAction This flag indicates if the parameter 'action' should
 * be included. When false, not even the symbol '?' at the beginning will be
 * included.
 * @param string $action This parameter indicates a replacement for the current
 * parameter 'action'.
 * @param string[] $except This is a list of parameters that should not appear.
 * @param boolean $includePosts When true, add POST parameters as GET parameters.
 * @return string Returns the built URI.
 */
function requestParams($addAction = true, $action = "", $except = array(), $includePosts = true) {
	$script = "";
	foreach($_REQUEST as $k => $v) {
		if(!$includePosts && isset($_POST[$k])) {
			continue;
		}
		if($k == "action" && (!$addAction || $action)) {
			continue;
		}
		if(in_array($k, $except)) {
			continue;
		}
		$script .= ($script ? "&" : "")."{$k}=".turlencode($v);
	}
	if($addAction) {
		$script = "?".($action ? "action={$action}&" : "")."{$script}";
	}
	return $script;
}
function getOptionsHelp($script, $params = array(), $texts = array(), $purpose = false) {
	empty($_SERVER["SHELL"]) && die("This funcition runs only on comand line");

	ksort($params);

	$optsList = "";
	$optsFull = "";
	foreach($params as $shortOpt => $longOpt) {
		$optsList .= "[";
		$hasValues = (strpos($shortOpt, ":") !== false);

		$cleanShortOpt = str_replace(":", "", $shortOpt);
		$cleanLongOpt = str_replace(":", "", $longOpt);

		$optsFull .= "\t-{$cleanShortOpt}";
		$optsList .= "-{$cleanShortOpt}";
		if($hasValues) {
			$optsFull .= " value";
			$optsList .= " value";
		}

		$optsFull .= ", --{$cleanLongOpt}";
		$optsList .= "|--{$cleanLongOpt}";
		if($hasValues) {
			$optsFull .= " value";
			$optsList .= " value";
		}
		$optsFull .= "\n";

		if(isset($texts[$longOpt])) {
			foreach(explode("\n",$texts[$longOpt]) as $line) {
				$optsFull .= "\t\t{$line}\n";
			}
		} else {
			$optsFull .= "\t\tNot documented option\n";
		}
		$optsFull .= "\n";
		$optsList .= "] ";
	}

	echo "Usage:\n";
	echo "\t{$_SERVER["_"]} '{$script}' {$optsList}\n";
	if($purpose) {
		echo "\n";
		echo "Purpose:\n";
		echo "\t{$purpose}\n";
	}
	echo "\n";
	echo "Options:\n";
	echo $optsFull;
}
function recursive_unlink($path, $keepFather = false) {
	$out = array();

	if(is_readable($path)) {
		if(is_dir($path)) {
			if($dir = @opendir($path)) {
				while($entry = readdir($dir)) {
					if($entry != ".." && $entry != ".") {
						foreach(recursive_unlink($path.DIRECTORY_SEPARATOR.$entry, false) as $v) {
							array_push($out, $v);
						}
					}
				}
				closedir($dir);
				if(!$keepFather) {
					if(!@rmdir($path)) {
						array_push($out, error_get_last());
					}
				}
			} else {
				array_push($out, error_get_last());
			}
		} else {
			if(!@unlink($path)) {
				array_push($out, error_get_last());
			}
		}
	} else {
		array_push($out, "$path: No such a file o directory");
	}

	return $out;
}
function startTheme() {
	global $wcTheme;
	global $wcThemeClasses;
	global $wcThemeDefaults;
	global $wcDefaults;
	global $wctDefaults;

	if(class_exists($wcThemeClasses[$wcDefaults["theme"]])) {
		$wctDefaults = $wcThemeDefaults[$wcDefaults["theme"]];
		$wcTheme = new $wcThemeClasses[$wcDefaults["theme"]]();
	} else {
		trigger_error(__FUNCTION__."(): Class '{$wcThemeClasses[$wcDefaults["theme"]]}' does not exists.", E_USER_ERROR);
	}
}
function startMobileTheme() {
	global $wcTheme;
	global $wcThemeClasses;
	global $wcThemeDefaults;
	global $wcDefaults;
	global $wctDefaults;

	if(class_exists($wcThemeClasses[$wcDefaults["theme-mobile"]])) {
		$wctDefaults = $wcThemeDefaults[$wcDefaults["theme-mobile"]];
		$wcTheme = new $wcThemeClasses[$wcDefaults["theme-mobile"]]();
	} else {
		trigger_error(__FUNCTION__."(): Class '{$wcThemeClasses[$wcDefaults["theme-mobile"]]}' does not exists.", E_USER_ERROR);
	}
}
class ImagePath {
	public $path = '';
	public $lpath = '';
	public $name = '';
	public $ext = '';
}

function cropImage($path, $thumbWidth, &$errmsg = "") {
	$ok = true;

	$info = pathinfo($path);
	$ext = strtolower($info['extension']);

	switch($ext) {
		case 'jpg':
		case 'jpeg':
			$img = imagecreatefromjpeg("{$path}");
			break;
		case 'png':
			$img = imagecreatefrompng("{$path}");
			break;
		default:
			$ok = false;
			$errmsg = "unsupported extension {$ext}";
	}
	if($ok && $img === false) {
		$ok = false;
		$errmsg = "imagecreatefrom...";
	}
	if($ok) {
		/*
		 * load image and get image size.
		 */
		$width = imagesx($img);
		$height = imagesy($img);
		if($width === false || $height === false) {
			$ok = false;
			$errmsg = "imagesxy";
		} else {
			/*
			 * calculate thumbnail size.
			 */
			if($width > $height) {
				$new_width = $thumbWidth;
				$new_height = floor($height * ($thumbWidth / $width));
			} else {
				$new_width = floor($width * ($thumbWidth / $height));
				$new_height = $thumbWidth;
			}
		}
	}

	/*
	 * create a new temporary image.
	 */
	if($ok) {
		$tmp_img = imagecreatetruecolor($new_width, $new_height);
		if($tmp_img === false) {
			$ok = false;
			$errmsg = "imagecreatetruecolor";
		}
	}
	/*
	 * copy and resize old image into new image.
	 */
	if($ok) {
		$ok = imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		if(!$ok) {
			$errmsg = "imagecopyresampled";
		}
	}
	if($ok) {
		$ok = unlink($path);
	}
	if($ok) {
		/*
		 * save thumbnail into a file.
		 */
		switch($ext) {
			case 'jpg':
			case 'jpeg':
				$ok = imagejpeg($tmp_img, "{$path}");
				break;
			case 'png':
				$ok = imagepng($tmp_img, "{$path}");
				break;
		}
	}
	if(!$ok) {
		$errmsg = "image...";
	}

	return $ok;
}
function getBinaryFullPath($binary) {
	$found = "";

	if(WCSanitizer::IsAbsolutePath($binary)) {
		if(is_executable($binary)) {
			$found = $binary;
		}
	} else {
		$bin = $binary;
		if(DIRECTORY_SEPARATOR == "/") {
			$pathVar = "\$PATH";
		} else {
			if(!preg_match('/\.exe$/', $bin)) {
				$bin .= ".exe";
			}
			$pathVar = "%PATH%";
		}

		foreach(explode(PATH_SEPARATOR,exec("echo {$pathVar}")) as $path) {
			$aux = $path.DIRECTORY_SEPARATOR.$bin;
			if(is_executable($aux)) {
				$found = $aux;
				break;
			}
		}
	}

	return $found ? $found : false;
}
?>
